package br.com.inner.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport implements ServletRequestAware, ServletContextAware{

	private static final long serialVersionUID = 5156288255337069381L;

    private String contentType;
    private File upload;
    private String fileName;
    private String caption;
    
    private HttpServletRequest request;
    private ServletContext s;
    
    public void setServletRequest(HttpServletRequest httpServletRequest) {
		this.request = httpServletRequest;		
	}
    
    public HttpServletRequest getRequest(){
    	return request;
    }
    
    public void setServletContext(ServletContext arg0) {
		s = arg0;
	}

    // since we are using <s:file name="upload" .../> the file name will be
    // obtained through getter/setter of <file-tag-name>FileName
    public String getUploadFileName() {
        return fileName;
    }
    public void setUploadFileName(String fileName) {
        this.fileName = fileName;
    }


    // since we are using <s:file name="upload" ... /> the content type will be
    // obtained through getter/setter of <file-tag-name>ContentType
    public String getUploadContentType() {
        return contentType;
    }
    public void setUploadContentType(String contentType) {
        this.contentType = contentType;
    }


    // since we are using <s:file name="upload" ... /> the File itself will be
    // obtained through getter/setter of <file-tag-name>
    public File getUpload() {
        return upload;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getCaption() {
        return caption;
    }
    public void setCaption(String caption) {
        this.caption = caption;
    }

    public String input() throws Exception {
        return SUCCESS;
    }

    /*public String upload() throws Exception  {
    	File f = new File("C:\\Marcelo");
    	DiskFileItemFactory factory = new DiskFileItemFactory();
    	factory.setRepository(f);
    	ServletFileUpload uploadfu = new ServletFileUpload(factory);
    	Enumeration en = request.getAttributeNames();
    	while(en.hasMoreElements()){
    		System.out.println(en.nextElement());
    	}
    	List items = uploadfu.parseRequest(request);
    	//List items = getUpload();
    	Iterator iter = items.iterator();
    	while (iter.hasNext()) {
    	    FileItem item = (FileItem) iter.next();

    	    if (item.isFormField()) {
    	        processFormField(item);
    	    } else {
    	        processUploadedFile(item);
    	    }
    	}
        return SUCCESS;
    }*/
    
    public String doUpload() throws Exception{
    	//String uploadDir = s.getRealPath("WebContent\\Anexos\\");
    	System.out.println(getRequest().getContextPath());
    	String uploadDir = "C:\\Marcelo\\Projetos\\ProjInner\\WebContent\\Anexos\\";
    	File dirPath = new File(uploadDir);

        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        InputStream stream = new FileInputStream(upload);
        OutputStream bos = new FileOutputStream(uploadDir + fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        bos.close();        
        stream.close();
        
        getRequest().setAttribute("location", dirPath.getAbsolutePath()
                + upload.separatorChar + fileName);
        
        String link =
            getRequest().getContextPath() + "/resources" + "/" +
            getRequest().getRemoteUser() + "/";
        
        getRequest().setAttribute("link", link + fileName);
    	
    	return SUCCESS;
    }
    
    public void processFormField(FileItem item) throws Exception{
    	if (item.isFormField()) {
    	    String name = item.getFieldName();
    	    String value = item.getString();
    	    File diretorio = new File("C:\\Marcelo");
    	    if (!diretorio.exists()){
    	    	 diretorio.mkdir();
    	    }
    	    File file = new File(diretorio, name);
    	    FileOutputStream fos = new FileOutputStream(file);
    	    InputStream is = item.getInputStream();
    	    byte[] buffer = new byte[2048];
    	    int nLidos;
    	    while ((nLidos = is.read(buffer)) >= 0) {
    	    	fos.write(buffer, 0, nLidos);
    	    }
    	    fos.flush();
    	    fos.close();
    	}
    }
    
    public void processUploadedFile(FileItem item) throws Exception{
    	if (!item.isFormField()) {
    	    String fieldName = item.getFieldName();
    	    String fileName = item.getName();
    	    String contentType = item.getContentType();
    	    boolean isInMemory = item.isInMemory();
    	    long sizeInBytes = item.getSize();
    	    File diretorio = new File("C:\\Marcelo");
    	    if (!diretorio.exists()){
    	    	 diretorio.mkdir();
    	    }
    	    File file = new File(diretorio, fileName);
    	    FileOutputStream fos = new FileOutputStream(file);
    	    InputStream is = item.getInputStream();
    	    
    	    MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());
        	InputStream is1 = multipartRequest.getInputStream();
    	    
    	    byte[] buffer = new byte[2048];
    	    int nLidos;
    	    while ((nLidos = is.read(buffer)) >= 0) {
    	    	fos.write(buffer, 0, nLidos);
    	    }
    	    fos.flush();
    	    fos.close();
    	}
    }
}
